﻿using System.Diagnostics;

namespace RFIDReader
{
    public abstract class iPublicEntity : IMifare
    {
        public static iPublicEntity RequestAnyCard(ushort readerID, int timeout, RequestMode WAK)
        {
            ushort atq = 0;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            while (sw.ElapsedMilliseconds < timeout)
            {
                var last = MasterRD.rf_ISO14443A_Request(readerID, WAK, ref atq);
                if (last == MResponse.LIB_SUCCESS)
                    break;
            }
            sw.Stop();
            switch(atq)
            {
                case MIFARE_ULTRALC:
                    return new UltraLightCPublicEntity();
            }
            throw new System.Exception("Card Not Found, or Implemented");
        }
        public abstract bool SelectCard(ushort readerID, int timeout, RequestMode WAK);
        public CardResponse ReadCard(ushort readerID, bool hasSAMCard)
        {
            if (ReadPublicData() != CardResponse.GoodRead)
            {
                return LastAction;
            }
            if (hasSAMCard)
            {
                if (Authenticate() != CardResponse.GoodRead)
                {
                    return LastAction;
                }
                if (ReadSecureData() != CardResponse.GoodRead)
                {
                    return LastAction;
                }
            }
            return CardResponse.GoodRead; 
        }

        protected abstract CardResponse ReadPublicData();
        protected abstract CardResponse Authenticate();
        protected abstract CardResponse ReadSecureData();
        protected abstract CardResponse GetError(MResponse mr);
        protected ushort ReaderID;
        protected CardResponse LastAction;
        protected const ushort MIFARE_CLASSIC = 0x0004;
        protected const ushort MIFARE_ULTRALC = 0x0044;
        protected const ushort MIFARE_DESFIRE = 0x0344;
    }
}
